package src.estore.network;

import java.io.*;
import java.net.*;
import java.util.List;
import src.estore.Product;
import src.estore.ProductService;

public class EStoreServer {
    private ProductService productService;

    public EStoreServer() {
        this.productService = new ProductService();
    }

    public void startServer() {
        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            System.out.println("服务器已启动，监听端口 8888...");

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("接收到客户端连接: " + clientSocket.getInetAddress());

                // 在新线程中处理客户端请求，避免阻塞
                new Thread(() -> handleClient(clientSocket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handleClient(Socket clientSocket) {
        try (ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream())) {

            // 读取客户端请求
            String request = (String) input.readObject();
            System.out.println("接收到客户端请求: " + request);

            // 根据请求处理业务逻辑
            Object response = processRequest(request);

            // 返回响应
            output.writeObject(response);
            output.flush();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Object processRequest(String request) {
        switch (request) {
            case "GET_ALL_PRODUCTS":
                return productService.getAllProducts();
            // 可以添加其他请求处理
            default:
                return "未知请求: " + request;
        }
    }

    public static void main(String[] args) {
        EStoreServer server = new EStoreServer();
        server.startServer();
    }
}